<?php

/* * 
 * 分类
 */
namespace Api\Model;
use Think\Model;
class CategoryModel extends Model {

    //映射
    protected $_map = array(

    );

    public function getCategoryById($id) {

        $category = $this->where(array('category_id' => $id))->find();

        return $category;
        
    }

    public function getCategoryByIds($ids) {

        $map['category_id'] = array('in', $ids);

        $list = $this
            ->field("category_id, category_name")
            ->where($map)
            ->select();

        return $list;

    }

    //获取分类列表
    public function getCategoryList($categoryStatus='', $categoryType='', $challengeType='', $isUser=false, $userId='') {

        if(!isNullOrEmpty($categoryStatus)) {
            $map['category_status'] = $categoryStatus;
        }

        if(!isNullOrEmpty($categoryType)) {
            $map['category_type'] = $categoryType;
        }

        if(!isNullOrEmpty($challengeType)) {
            $map['challenge_type'] = $challengeType;
        }

        $list = $this
            ->field('category_id, category_name')
            ->where($map)
            ->select();

        if($isUser) {

            $user = D('user')->getUserById($userId);

            //获取用户选择的分类
            if(!isNullOrEmpty($user['category_json'])) {
                $userTagList = unserialize($user['category_json']);
            } else {
                $userTagList = array();
            }

            if(!isNullOrEmpty($userTagList)) {

                $userCategoryIdList = array_column($userTagList, 'category_id');

                foreach ($list as &$item) {

                    if(in_array($item['category_id'], $userCategoryIdList)) {
                        $item['is_select'] = true;
                    } else {
                        $item['is_select'] = false;
                    }

                }

            }

        }

        return $list;

    }

    //根据用户获取分类
    public function getCategoryListByUserId($userId, $categoryType) {

        $user = D('user')->getUserById($userId);

        //获取系统分类
        $systemTagList = $this->getCategoryList(C('CATEGORY_STATUS.SYSTEM'),$categoryType);

        //获取用户选择的分类
        if(!isNullOrEmpty($user['category_json'])) {
            $userTagList = unserialize($user['category_json']);
        } else {
            $userTagList = array();
        }

        $list = array_merge($systemTagList,$userTagList);

        return $list;

    }

    //增加分类选择次数
    public function updateCategorySelectTimes($categoryIds) {

        $map['category_id'] = array('in', $categoryIds);

        $this->where($map)->setInc('select_times', 1);

    }

}

